package com.example.zp;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import java.util.List;


public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {

    // 当前app 运行环境参数
    private Context context;
    private List<String> list;
    private List<Integer> imgList;

    private View inflater;

    public Adapter(Context context, List<String> list, List<Integer> imgList) {
        this.context = context;
        this.list = list;
        this.imgList = imgList;

        notifyDataSetChanged();
    }

    @Override
    public Adapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // item xml文件
        inflater = LayoutInflater.from(context).inflate(R.layout.item, viewGroup, false);
        MyViewHolder myViewHolder = new MyViewHolder(inflater);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(Adapter.MyViewHolder holder, int position) {
        // 将list 中的值绑定到 Adapter中
        holder.textView.setText(list.get(position));
        holder.imageView.setImageResource(imgList.get(position));
    }

    @Override
    public int getItemCount() {
        // 返回list的长度
        return list.size();
    }

    public void onItemDismiss(int position) {
        if (position < 0 || position > getItemCount()) {
            return;
        }

        list.remove(position);
        notifyItemRemoved(position);

        // 解决 RecyclerView 删除 Item 导致位置错乱的问题
        if(position != list.size()) {
            notifyItemRangeChanged(position, list.size() - position);
        }
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView textView;
        public MyViewHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textView_item);
            imageView = itemView.findViewById(R.id.imageView);
        }
    }

}
